<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import type { LoginInfo } from '@/api/model/model'
import axios from 'axios'
import { querySubject, getSubjectById, addSubject, updateSubject, deleteSubjectByIds } from '@/api/subject/index'
import { queryEmpLists } from '@/api/emp/index'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
// 获取token
import { useLoginEmpStore } from '@/stores/loginEmp'
const loginEmpStore = useLoginEmpStore();
const loginInfo = ref<LoginInfo>(loginEmpStore.getLoginInfo());

// 页面顶部的搜索
const searchForm = ref({
    name: '',
    principalId: '',
})

onMounted(() => {
    // 查询学科列表
    query();
    // 查询所有的员工
    queryEmps();
});

const query = async () => {
    const res = await querySubject(searchForm.value.name, searchForm.value.principalId, currentPage.value, pageSize.value);
    subjeList.value = res.data.rows
    total.value = res.data.total
}

const queryEmps = async () => {
    const res = await queryEmpLists();
    empList.value = res.data;
}

const clear = () => {
    searchForm.value = { name: '', principalId: '' }
}

const empList = ref();
// 页面主体的数据列表
const subjeList = ref();
// 分页的数据
let currentPage = ref<number>(1)
const pageSize = ref<number>(5);
const total = ref<number>(0);
const handleSizeChange = () => {
    currentPage = ref<number>(1);
    query();
}
const handleCurrentChange = () => {
    query();
}





const dialogFromRef = ref();
// dialog弹框
const dialogFormVisible = ref<boolean>(false)
const clazzList = ref()
const dialogTitle = ref<string>('')
const insertOrUpdateForm = ref({
    id: '',
    name: '',
    empId: '',
    introduce: '',
});
const formLabelWidth = "90px";
// 新增
const openAddDialog = () => {
    dialogFormVisible.value = true;
    dialogTitle.value = "新增学科";
}




// 更新
const handleEdit = async (idx,row) => {
    if (!row.id) {
        return;
    }
    // 展示弹框
    dialogFormVisible.value = true;
    dialogTitle.value = "修改学员";
    // 回显查询，参数是id
    const res = await getSubjectById(row.id);
    insertOrUpdateForm.value = res.data;
}

const insertOrUpdate = (formEL: FormInstance | undefined) => {
    if (!formEL) {
        return;
    }
    // 先校验表单的格式
    formEL.validate(async (valid) => {
        if (valid) {
            // 校验通过
            let res = null;
            let insertFlag = null;
            if (insertOrUpdateForm.value.id) {//修改
                insertFlag = false;
                res = await updateSubject(insertOrUpdateForm.value);
            } else {// 新增
                insertFlag = true;
                res = await addSubject(insertOrUpdateForm.value);
            }
            if (!res.code) {
                ElMessage.error(res.msg);
            } else {
                // 隐藏dialog
                dialogFormVisible.value = false;
                // 清空dialog，通过dialog的回调统一处理
                ElMessage({ type: 'success', message: insertFlag ? '添加成功' : '修改成功', })
                query();
            }
        }
    });

}

const handleDelete = (idx,row) => {
    ElMessageBox.confirm('您确认删除此数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            const res = await deleteSubjectByIds(row.id);
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();
            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}
// 保存所有选中的行的id
const selectIds = ref<(number | undefined)[]>([])
// 入参：是所有的选中的行的数据的数组
const handleSelectionChange = (idx,rows) => {
    // 重置selectIds
    selectIds.value = []
    if (!selectIds) {
        return;
    }
    if (!rows || rows.length <= 0) {
        selectIds.value = []
    } else {
        for (let i = 0; i < rows.length; i++) {
            selectIds.value.push(rows[i].id);
        }

    }
}




const batchDelete = () => {
    // 先判断seleectIds是否有值
    if (!selectIds.value || selectIds.value.length <= 0) {
        ElMessage({ type: 'error', message: '没有选中任何数据' })
        return;
    }
    ElMessageBox.confirm('您确认删除这些数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            // 数组元素拼接：selectIds.value.join(",")
            const res = await deleteSubjectByIds(selectIds.value.join(","));
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();

            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}


// 表单校验
const rules = ref({
    name: [
        { required: true, message: '名称不能为空', trigger: 'blur' },
    ],
})



// dialog关闭的时候自动回调
function dialogClose() {
    if (!dialogFromRef || !dialogFromRef.value) {
        return;
    }
    insertOrUpdateForm.value =
    {
        id: '',
        name: '',
        empId: '',
        introduce: '',
    }
    // 重置form校验规则
    dialogFromRef.value.resetFields();
}



</script>
<template>
    <span class="title">学科管理 </span>

    <!----------------------------------搜索框-------------------------------------->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="学科名称">
            <el-input v-model="searchForm.name" placeholder="请输入学科名称" style="width:200px" clearable />
        </el-form-item>
        <el-form-item label="学科负责人">
            <el-select v-model="searchForm.principalId" placeholder="请选择" style="width:200px" clearable>
                <el-option :label="emp.name" :value="emp.id" v-for="(emp, index) in empList" :key="emp.id" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>
            <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
    </el-form>

    <el-button type="success" @click="openAddDialog">+ 新增学科</el-button>
    <el-button type="danger" @click="batchDelete">- 批量删除</el-button>

    <!-----------------------页面主体的数据列表-------------------------------->
    <el-table :data="subjeList" border style="width: 100%; margin-top:10px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="学科名称" width="110" align="center" />
        <el-table-column prop="empName" label="学科负责人" width="150" align="center" />
        <el-table-column prop="introduce" label="学科介绍" show-overflow-tooltip width="280" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200" align="center" />
        <el-table-column prop="updateTime" label="最后修改时间" width="200" align="center" />
        <el-table-column label="操作" align="center">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                    编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!----------------------------------分页组件---------------------------------------->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top:10px" />




    <!----------------------------------dialog弹框-------------------------------------->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" @close="dialogClose">
        <el-form :model="insertOrUpdateForm" ref="dialogFromRef" :rules="rules">

            <el-form-item label="学科名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="insertOrUpdateForm.name" autocomplete="off" placeholder="请输入姓名" clearable />
            </el-form-item>

            <el-form-item label="学科负责人" :label-width="formLabelWidth">
                <el-select v-model="insertOrUpdateForm.empId" placeholder="请选择" style="width: 100%">
                    <el-option :label="emp.name" :value="emp.id" v-for="(emp, index) in empList" :key="emp.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="学科介绍" :label-width="formLabelWidth" prop="introduce">
                <el-input v-model="insertOrUpdateForm.introduce" autocomplete="off" placeholder="请输入学科介绍" clearable />
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="insertOrUpdate(dialogFromRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style scope>
.title {
    font-size: 20px;
    font-weight: 600;
}

.demo-form-inline {
    margin-top: 10px
}

.required-label .el-form-item__label:before {
    content: '*';
    color: red;
    margin-right: 2px;
}

.avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
</style>